package cn.hnshxy.dch;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;

@WebServlet("/api")
public class API extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private JSONObject getBody(HttpServletRequest request) {
		try {
			String contentType = request.getContentType();
			System.out.println(contentType);
			if(contentType.equals("application/json")) {
				byte[]buffer=new byte[1024];
				ServletInputStream is=request.getInputStream();
				ByteArrayOutputStream bs = new ByteArrayOutputStream();
				while(true){
					int len=is.read(buffer);
					if(len==-1)break;
					bs.write(buffer,0,len);
				}
				String body=bs.toString("utf-8");
				return JSONObject.parseObject(body);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject jo = getBody(request);
		JSONObject r=new JSONObject();
		r.put("ok", true);
		try {
			if(jo==null)throw new Exception("调用参数错误，请阅读开发文档~");
			String op = jo.getString("op");
			if(op==null)throw new Exception("未知操作请求，请阅读开发文档~");
			HttpSession session = request.getSession();
			String first=(String)session.getAttribute("first");
			if(op.equals("begin")) {
				session.removeAttribute("first");
			}else if(op.equals("check")) {
				String cy = jo.getString("cy");
				if(cy==null)throw new Exception("必须提供要接龙的成语~");
				cy=cy.trim();
				if(cy.length()<3||cy.length()>14)throw new Exception("成语应该在3到14个汉字之内~");
				if(first!=null&&!cy.startsWith(first))throw new Exception("输入的成语必须以“"+first+"”字开头~");
				
				DbHelper db = new DbHelper();
				List<Map<String,Object>> list = db.executeQuery("select cy from chengyu where cy=?", cy);
				if(list.size()==0)throw new Exception("Sorry，你输入的“"+cy+"”不是成语！");
				list = db.executeQuery("select cy from chengyu where first=? order by rand() limit 1", cy.substring(cy.length()-1));
				if(list.size()==1) {
					cy=(String) list.get(0).get("cy");//计算机接龙的成语
					first=cy.substring(cy.length()-1);
					r.put("cy",cy);
					r.put("first", first);
					session.setAttribute("first", first);
				}
			}
		}catch(Exception e) {
			r.put("ok",false);
			r.put("msg", e.getMessage());
		}
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(r.toString());
		
//		response.setContentType("application/json; charset=UTF-8");
//		PrintWriter out = response.getWriter();
//		JSONObject jo = getBody(request);
//		if(jo==null)out.print("{\"mag\":\"非法json格式数据\"}");
//		else out.print(jo.toString());
		
//		request.setCharacterEncoding("utf-8");
//		String cy = request.getParameter("cy");
//		String time = request.getParameter("time");
//		response.setContentType("text/plain; charset=UTF-8");
//		PrintWriter pw = response.getWriter();
//		pw.print(cy+","+time);
	}
}
	